import { getsn, getScRstNo } from "@/utils/getsn"
import { UserInfo, PhotoType, getPhotoList } from "@/utils/public.js"
const addScRstSql =
	"select * from " +
	" (select COUNT(*) count ,SC_RST_NO" +
	"  from SC_RST_Table B " +
	"  WHERE B.CONS_NO = ? " +
	"  AND B.APP_NO = ?)  COUNT_SC_RST, " +
	" (select A.SC_PDTL_ID,count(SC_PDTL_ID) test1  " +
	"  from TS_DTL_Table A " +
	"  WHERE A.CONS_NO=? " +
	"  AND A.APP_NO=?) SC_DTL_ID ";
/**
 * 通过当前用户的org_no获取安检项目，和安检项目明细
 */
export function getSecurityProject(callBack, errorBack) {
	let queryScItemSql = {
		"whereClause": "select * from sc_item where M_ORG_NO = ? and SEQ_LEVEL = '1' AND USE_TYPE = '01'",
		"whereArgs": [UserInfo.ORG_NO]
	}
	AndroidApi.queryTableData(JSON.stringify(queryScItemSql), function(msg) {
		console.log(msg);
		if(msg.resultCode === '9999') {
			let result = msg.result;
			if(result && result.length > 0) {
				let count = 0;
				for(let scItem of result) {
					let scItemId = scItem.SC_ITEM_ID;
					let queryScItemDtlSql = {
						"whereClause": "select * from sc_item_dtl where sc_item_id = ?",
						"whereArgs": [scItemId]
					};
					AndroidApi.queryTableData(JSON.stringify(queryScItemDtlSql), function(msg) {
						count++;
						if(msg.resultCode = '9999') {
							let dtlResult = msg.result;
							scItem.SC_ITEM_DTL = dtlResult;
						}
						if(count === result.length) {
							callBack(result);
						}
					});
				}
			} else {
				callBack([])
			}
		} else {
			callBack([])
		}
	});
}

/**
 * 通过当前用户的org_no获取安检项目，和安检项目明细 子集
 * 获取安检项目明细的时候，需要关联隐患列表，将带有隐患，设置为 switchOn true
 */
export function getChildrenSecurityProject(scItemId, callBack, errorBack) {
	var app_no = localStorage.getItem("APP_NO");
	var cons_no = localStorage.getItem("CONS_NO");
	let queryScRstDtlSql = {
		"whereClause": "select C.* from " +
			"SC_RST_Table B, SC_RST_DTL_Table C " +
			"WHERE B.CONS_NO = ? " +
			"AND B.APP_NO = ? " +
			"AND B.SC_RST_NO = C.SC_RST_NO ",
		"whereArgs": [cons_no, app_no]
	};
	AndroidApi.queryTableData(JSON.stringify(queryScRstDtlSql), function(msg) {
		console.log(msg);
		if(msg.resultCode === '9999') {
			let scRstDtls = msg.result;
			if(scRstDtls) {
				console.log('这里是测试需要查看的数据');
				console.log(scRstDtls);
				let queryScItemSql = {
					"whereClause": "select * from sc_item where M_ORG_NO = ? and P_SC_ITEM_ID = ?",
					"whereArgs": [UserInfo.ORG_NO, scItemId]
				};
				AndroidApi.queryTableData(JSON.stringify(queryScItemSql), function(msg) {
					if(msg.resultCode === '9999') {
						let result = msg.result;
						if(result && result.length > 0) {
							let count = 0;
							for(let scItem of result) {
								let scItemId = scItem.SC_ITEM_ID;
								let scItemType = scItem.SC_ITEM_TYPE;
								let queryScItemDtlSql = {
									"whereClause": "select * from sc_item_dtl where sc_item_id = ?",
									"whereArgs": [scItemId]
								};
								AndroidApi.queryTableData(JSON.stringify(queryScItemDtlSql), function(msg) {
									count++;
									if(msg.resultCode === '9999') {
										let dtlResult = msg.result;
										for(let tmp of dtlResult) {
											tmp.BUSY_NO = tmp.ATTR_CODE;
											tmp.SC_ITEM_TYPE = scItemType;
											for(let scRstDtl of scRstDtls) {
												if(scRstDtl.CODE_VAL === tmp.ATTR_CODE) {
													tmp.switchOn = true;
												}
											}
										}
										console.log("dtlResult" + dtlResult.length)
										getPhotoList(dtlResult, app_no, cons_no, PhotoType.securityProjectDtl, function(data) {
											console.log("加入图片的list")
											console.log(dtlResult)
											scItem.SC_ITEM_DTL = dtlResult;
											if(count === result.length) {
												callBack(result);
											}
										})
									} else {
										if(count === result.length) {
											callBack(result);
										}
									}

								});
							}
						} else {
							callBack([])
						}
					} else {
						callBack([])
					}
				});
			} else {
				callBack([])
			}
		} else {
			callBack([])
		}
	});

}

/**
 * 1、查询安检任务明细表的TS_DTL_Table.SC_PDTL_ID，
 * 	安检结果SC_RST_Table条数 count，
 * 	安检项目明细SC_RST_Table.SC_RST_NO
 * 2、当count<0，插入一条默认的SC_RST_Table（SC_RST_NO生成），
 * 	插入成功后，
 * 3、插入隐患列表SC_RST_DTL_Table
 * 4、当count>0，执行3
 * @param {*} SC_RST_DTL 安检项目明细（SC_ITEM_TYPE从SC_RST表中获取填入）
 * @param {*} callBack 执行结束回调函数
 */
export function addScRstDtl(SC_RST_DTL, callBack) {
	var app_no = localStorage.getItem("APP_NO");
	var cons_no = localStorage.getItem("CONS_NO");
	let queryScRstDtlSql = {
		"whereClause": addScRstSql,
		"whereArgs": [cons_no, app_no, cons_no, app_no, cons_no, app_no]
	};
	AndroidApi.queryTableData(JSON.stringify(queryScRstDtlSql), function(msg) {
		console.log(msg);
		if(msg.resultCode === '9999') {
			let result = msg.result;
			console.log()
			if(result && result.length > 0) {
				let count = result[0].count;
				let SC_PDTL_ID = result[0].SC_PDTL_ID;
				let SC_RST_NO = result[0].SC_RST_NO;
				//当安检明细表不存在的时候，先创建安检明细表后，在添加隐患信息
				if((typeof count === 'number' ? count : Number(count)) <= 0) {
					let scRstNo = getScRstNo(app_no);
					let insertScRstSql = {
						"tableName": "SC_RST_Table",
						"contentValues": [{
							SC_PDTL_ID: SC_PDTL_ID,
							SC_RST_NO: scRstNo,
							APP_NO: app_no,
							CONS_NO: cons_no
						}]
					};
					console.log(insertScRstSql);
					AndroidApi.insert(JSON.stringify(insertScRstSql), function(msg) {
						// AndroidApi.alert(JSON.stringify(insertScRstSql));
						if(msg.resultCode === '9999') {
							addScRstDtlSql(SC_RST_DTL, scRstNo, callBack);
						} else {
							callBack("插入安检结果明细失败");
						}
					});
				} else {
					addScRstDtlSql(SC_RST_DTL, SC_RST_NO, callBack);
				}
			} else {
				callBack("AndroidApi.queryTableData出参格式异常!")
			}
		} else {
			callBack("获取安检结果表数目，和任务明细TS_DTL_Table获取失败！")
		}
	});
}

/**
 * 判断安检结果表是否存在，不存在则创建表
 * @param {*} app_no 
 * @param {*} cons_no 
 * @param {*} callBack 
 */
export function addScRst(app_no, cons_no, callBack) {
	let queryScRstDtlSql = {
		"whereClause": addScRstSql,
		"whereArgs": [cons_no, app_no, cons_no, app_no, cons_no, app_no]
	};

	AndroidApi.queryTableData(JSON.stringify(queryScRstDtlSql), function(msg) {
		console.log(msg);

		if(msg.resultCode === '9999') {
			let result = msg.result;
			if(result && result.length > 0) {
				let count = result[0].count;
				let SC_PDTL_ID = result[0].SC_PDTL_ID;
				let SC_RST_NO = result[0].SC_RST_NO;
				//当安检明细表不存在的时候，先创建安检明细表后，在添加隐患信息

				if((typeof count === 'number' ? count : Number(count)) <= 0) {

					// const sn="11";
					// let NUM="";
					// const DATA=new Date();
					// const YEARS=DATA.getFullYear();
					// const MONTHS=Number(DATA.getMonth())+1<10?"0"+(Number(DATA.getMonth())+1):Number(DATA.getMonth())+1;
					// const DAYS=DATA.getDate()<10?"0"+DATA.getDate():DATA.getDate();
					// const HOURS=DATA.getHours()<10?"0"+DATA.getHours():DATA.getHours();
					// const MINUTES=DATA.getMinutes()<10?"0"+DATA.getMinutes():DATA.getMinutes();
					// const SECONDS=DATA.getSeconds()<10?"0"+DATA.getSeconds():DATA.getSeconds();
					// const TIMESTAMP=YEARS+MONTHS+DAYS+HOURS+MINUTES+SECONDS;
					// let scRstNo = sn + app_no + TIMESTAMP;
					let scRstNo = getScRstNo(app_no);
					console.log("每次打印出来的scRstNo" + scRstNo);
					let insertScRstSql = {
						"tableName": "SC_RST_Table",
						"contentValues": [{
							SC_PDTL_ID: SC_PDTL_ID,
							SC_RST_NO: scRstNo,
							APP_NO: app_no,
							CONS_NO: cons_no
						}]
					};
					console.log("insertScRstSql");
					console.log(insertScRstSql);
					AndroidApi.insert(JSON.stringify(insertScRstSql), function(msg) {
						// AndroidApi.alert(JSON.stringify(insertScRstSql));
						if(msg.resultCode === '9999') {

						} else {
							callBack("插入安检结果明细失败");
						}
					});
				}
			} else {
				callBack("AndroidApi.queryTableData出参格式异常!")
			}
		} else {
			callBack("获取安检结果表数目，和任务明细TS_DTL_Table获取失败！")
		}
	});
}
/**
 * 添加隐患信息
 * @param {*} SC_RST_DTL 安检项目明细（SC_ITEM_TYPE从SC_RST表中获取填入）
 */
function addScRstDtlSql(SC_RST_DTL, SC_RST_NO, callBack) {
	let insertScRstDtlSql = {
		"tableName": "SC_RST_DTL_Table",
		"contentValues": [{
			SC_ITEM_TYPE: SC_RST_DTL.SC_ITEM_TYPE,
			ATTR_NAME: SC_RST_DTL.ATTR_NAME,
			CODE_VAL: SC_RST_DTL.ATTR_CODE,
			CORR_STYLE: SC_RST_DTL.CORR_STYLE,
			SC_RST_NO: SC_RST_NO
		}]
	};
	console.log("ScRstDtlSql插入入参");
	console.log(insertScRstDtlSql);
	AndroidApi.insert(JSON.stringify(insertScRstDtlSql), function(msg) {
		if(msg.resultCode === '9999') {
			callBack("插入成功！");
		} else {
			callBack("插入隐患列表失败");
		}
	});
}

export function getScRstDtl(successCall) {
	var app_no = localStorage.getItem("APP_NO");
	var cons_no = localStorage.getItem("CONS_NO");
	let queryScRstDtlSql = {
		"whereClause": "select C.*,D.* " +
			" from SC_RST_Table B, SC_RST_DTL_Table C ,(SELECT SID.SC_HANDLE_MODE CORR_STYLE_ITEM,SID.ATTR_CODE,SCI_TYPE_NAME,(SELECT SCI_TYPE_NAME FROM SC_ITEM WHERE SI.P_SC_ITEM_ID = SC_ITEM.SC_ITEM_ID) P_SCI_TYPE_NAME FROM SC_ITEM_DTL SID,SC_ITEM SI WHERE SI.M_ORG_NO=? AND SID.SC_ITEM_ID=SI.SC_ITEM_ID) D " +
			" WHERE B.CONS_NO = ? " +
			" AND B.APP_NO = ? " +
			" AND B.SC_RST_NO = C.SC_RST_NO " +
			" AND D.ATTR_CODE = C.CODE_VAL",
		"whereArgs": [UserInfo.ORG_NO, cons_no, app_no]
	};
	AndroidApi.queryTableData(JSON.stringify(queryScRstDtlSql), function(msg) {
		console.log("----------------------------------------------------")
		console.log(msg);
		if(msg.resultCode === '9999') {
			let scRstDtls = msg.result;
			if(scRstDtls && scRstDtls.length > 0) {
				scRstDtls.forEach(function(scRstDtl) {
					scRstDtl.BUSY_NO = scRstDtl.CODE_VAL;
				})
				getPhotoList(scRstDtls, app_no, cons_no, PhotoType.securityProjectDtl, function(data) {
					successCall(data);
				})
			} else {
				successCall();
			}
		} else {
			successCall();
		}
	});
}

export function uploadSecurity(successCall) {
	var app_no = localStorage.getItem("APP_NO");
	var cons_no = localStorage.getItem("CONS_NO");
	let queryScRstDtlSql = {
		"whereClause": "select C.*,D.* " +
			" from TS_DTL_Table A, SC_RST_Table B, SC_RST_DTL_Table C ,(SELECT SID.ATTR_CODE,SCI_TYPE_NAME,(SELECT SCI_TYPE_NAME FROM SC_ITEM WHERE SI.P_SC_ITEM_ID = SC_ITEM.SC_ITEM_ID) P_SCI_TYPE_NAME FROM SC_ITEM_DTL SID,SC_ITEM SI WHERE SI.M_ORG_NO=? AND SID.SC_ITEM_ID=SI.SC_ITEM_ID) D " +
			" WHERE A.CONS_NO = ? " +
			" AND A.APP_NO = ? " +
			" AND A.SC_PDTL_ID = B.SC_PDTL_ID " +
			" AND B.SC_RST_NO = C.SC_RST_NO " +
			" AND D.ATTR_CODE = C.CODE_VAL",
		"whereArgs": [UserInfo.ORG_NO, cons_no, app_no]
	};
	AndroidApi.queryTableData(JSON.stringify(queryScRstDtlSql), function(msg) {
		console.log(msg);
		if(msg.resultCode === '9999') {
			let scRstDtls = msg.result;
			if(scRstDtls && scRstDtls.length > 0) {
				successCall(scRstDtls);
			} else {
				successCall();
			}
		} else {
			successCall();
		}
	});
}

export function delScRstDtl(ATTR_CODE, successCall) {
	var app_no = localStorage.getItem("APP_NO");
	var cons_no = localStorage.getItem("CONS_NO");
	let queryScRstDtlSql = {
		"whereClause": "select B.SC_RST_NO  " +
			"from TS_DTL_Table A , SC_RST_Table B " +
			"WHERE A.CONS_NO=? " +
			"AND A.APP_NO=? " +
			"AND A.SC_PDTL_ID = B.SC_PDTL_ID  ",
		"whereArgs": [cons_no, app_no]
	};
	AndroidApi.queryTableData(JSON.stringify(queryScRstDtlSql), function(msg) {
		// AndroidApi.alert(JSON.stringify(msg));
		if(msg.resultCode === '9999') {
			let result = msg.result;
			if(result && result.length > 0) {
				let SC_RST_NO = result[0].SC_RST_NO;
				let delScRstDtlSql = {
					"tableName": "SC_RST_DTL_Table",
					"whereClause": "SC_RST_NO=? AND CODE_VAL = ?",
					"whereArgs": [SC_RST_NO, ATTR_CODE]
				}
				AndroidApi.deletes(JSON.stringify(delScRstDtlSql), function(msg) {
					// "SC_RST_DTL_Table删除记录:" + JSON.stringify(msg)
					// AndroidApi.alert(JSON.stringify(msg));
					successCall("删除隐患成功！");
				});
			} else {
				successCall("数据异常！");
			}
		} else {
			successCall("数据异常！");
		}
	});

}
